#include"FuncHandler.hpp"
#include"../Protocol/MapProtocol.hpp"
#include"rapidjson/document.h"
#include"rapidjson/stringbuffer.h"
#include"rapidjson/writer.h"
#include"FuncApp.hpp"
#include"../DataBase/EvSceneData.hpp"
#include"../Protocol/Seralize.hpp"
#include<string>
#include"SceneSim.hpp"
#include"RpcClient.hpp"


namespace SC_SUN
{

    namespace Details
    {
        using namespace MMFNetwork;
        using namespace MMFSerialize;

        //解析网络消息
        template<typename T>
        void ParseMessage(MMFMessageHeader* pkg, T& msg)
        {
            char* data = pkg->mName + pkg->mNameBytes;
            SerialOutBuffer out(data, pkg->mDataBytes - (uint32_t(pkg->mName - (char*)pkg) + pkg->mNameBytes));
            out << msg;
        }
    }


    FuncHandler::FuncHandler(FuncService& service, FuncApp& app)
        :mService(service)
        ,mApp(app)
    {

    }


    FuncHandler::~FuncHandler()
    {

    }


    void FuncHandler::Start()
    {
        RegisterHandler();
    }


    void FuncHandler::Stop()
    {
        
    }


    void FuncHandler::RegisterHandler()
    {
        using namespace MMFNetwork;
        using namespace MMFSerialize;
        using namespace rapidjson;
        
        //场景切换
        mService.Dispathter().RegisterCallback(SC_SET_SCENE_MSG, [this](uWS::WebSocket<false,true,void*>* ws, MMFNetwork::MMFMessageHeader* pkg){
            ScSetSceneMSG msg = {};
            Details::ParseMessage(pkg, msg);

            //获取要设置的场景
            std::string scene = msg.msg;

            //调用处理
            mApp.GetSceneSim()->SetCurScene(scene);

            //回消息
            mService.SendMsgTo<ScSetSceneMSG>(ws, SC_SATELLITE_MSG, msg);
        });

        //获取场景列表
        mService.Dispathter().RegisterCallback(SC_GET_SCENE_LIST_MSG_JSON, [this](uWS::WebSocket<false,true,void*>* ws, MMFNetwork::MMFMessageHeader* pkg){
            ScGetSceneListMSGJson msg = {};
            Details::ParseMessage(pkg, msg);

            //获取场景信息
            ScGetSceneListMSG sceneReq;
            sceneReq.scenes.push_back(SC_GET_SCENE_LIST_MSG);
            mApp.GetRpc()->SendMsg<ScGetSceneListMSG>(SC_GET_SCENE_LIST_MSG, sceneReq);
            mApp.GetRpc()->RecvMsg<ScGetSceneListMSG>(sceneReq);

            //包装数据
            Document doc2;
            doc2.SetObject();

            Value parents(kArrayType);
            for (int i = 0; i < sceneReq.scenes.size(); i++)
            {
                parents.PushBack(Value(sceneReq.scenes[i].data(), doc2.GetAllocator()), doc2.GetAllocator());
            }

            //数据转换成字符串
            StringBuffer buffer;
            Writer<StringBuffer> writer(buffer);
            doc2.Accept(writer);
            std::string jsonStr = buffer.GetString();

            //回消息
            msg.scenes = std::string(jsonStr);
            mService.SendMsgTo<ScGetSceneListMSGJson>(ws, SC_GET_SCENE_LIST_MSG_JSON, msg);
        });

    }
}